package org.turbobytes.unikey.util.db;

import org.turbobytes.unikey.util.StringUtil;
import org.turbobytes.unikey.util.db.metadata.DbType;
import org.turbobytes.unikey.util.db.metadata.Metadata;
import static org.turbobytes.unikey.util.db.metadata.DbType.*;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

/**
 * Common db util operations
 *
 * @author Ganeshji Marwaha
 * @since Aug 8, 2010
 */
public class DbUtil {

  public static DbType getDbType(Connection connection) {
    try {
      DatabaseMetaData metaData = connection.getMetaData();
      String dbName = metaData.getDatabaseProductName();
      for(DbType type : values()) {
        if(StringUtil.equalsIgnoreCase(type.getName(), dbName)) {
          return type;
        }
      }
    } catch(SQLException e) {
      throw new DbException(e);
    }
    return UNKNOWN;
  }

  public static Metadata getMetadata(Connection connection) {
    return getDbType(connection).getMetadata();
  }
}
